<template>
  <div class="device-list-container">
    <div class="header-actions">
      <div class="left-actions">
        <el-button type="primary" @click="addDevice" :icon="Plus">添加设备</el-button>
        <el-button @click="refreshList" :icon="Refresh">刷新</el-button>
      </div>
      <div class="right-actions">
        <el-input
          v-model="searchParams.keyword"
          placeholder="搜索设备名称/编号"
          clearable
          style="width: 220px; margin-right: 10px"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="searchParams.type" placeholder="设备类型" clearable style="width: 150px; margin-right: 10px">
          <el-option label="LCD屏幕" value="LCD_SCREEN" />
          <el-option label="LED显示屏" value="LED_DISPLAY" />
          <el-option label="数字标牌" value="DIGITAL_SIGNAGE" />
          <el-option label="触摸屏" value="TOUCH_SCREEN" />
          <el-option label="信息亭" value="INTERACTIVE_KIOSK" />
          <el-option label="其他" value="OTHER" />
        </el-select>
        <el-select v-model="searchParams.status" placeholder="设备状态" clearable style="width: 120px; margin-right: 10px">
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
        <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
      </div>
    </div>

    <el-card class="list-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="devices"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="设备名称" width="150" />
        <el-table-column prop="deviceCode" label="设备编号" width="130" />
        <el-table-column prop="type" label="设备类型" width="130">
          <template #default="scope">
            {{ getDeviceTypeText(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="location" label="位置" min-width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="250">
          <template #default="scope">
            <el-button type="primary" link @click="viewDeviceDetail(scope.row.id)">
              详情
            </el-button>
            <el-button type="success" link @click="editDevice(scope.row.id)">
              编辑
            </el-button>
            <el-button 
              :type="scope.row.status === 0 ? 'success' : 'warning'" 
              link 
              @click="toggleDeviceStatus(scope.row)"
            >
              {{ scope.row.status === 0 ? '启用' : '禁用' }}
            </el-button>
            <el-button type="danger" link @click="confirmDeleteDevice(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus, Refresh } from '@element-plus/icons-vue';
import { getDeviceList, deleteDevice, enableDevice, disableDevice } from '@/api/device';

const router = useRouter();
const loading = ref(false);
const devices = ref([]);

// 分页数据
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
});

// 搜索参数
const searchParams = reactive({
  keyword: '',
  type: '',
  status: ''
});

// 获取设备列表
const fetchDevices = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchParams.keyword,
      type: searchParams.type,
      status: searchParams.status
    };
    const { data } = await getDeviceList(params);
    console.info("设备列表响应1:", data);
    if (data.code === 200) {
      devices.value = data.data.records;
      pagination.total = data.data.total;
    } else {
      ElMessage.error(data.message || '获取设备列表失败');
    }
  } catch (error) {
    console.error('获取设备列表失败:', error);
    ElMessage.error('获取设备列表失败');
  } finally {
    loading.value = false;
  }
};

// 查看设备详情
const viewDeviceDetail = (id) => {
  router.push(`/device-owner/devices/${id}`);
};

// 编辑设备
const editDevice = (id) => {
  router.push(`/device-owner/devices/edit/${id}`);
};

// 添加设备
const addDevice = () => {
  router.push('/device-owner/devices/add');
};

// 切换设备状态
const toggleDeviceStatus = async (device) => {
  try {
    let response;
    if (device.status === 0) {
      response = await enableDevice(device.id);
    } else {
      response = await disableDevice(device.id);
    }
    
    const { data } = response;
    if (data.code === 200) {
      ElMessage.success(device.status === 0 ? '设备已启用' : '设备已禁用');
      fetchDevices();
    } else {
      ElMessage.error(data.message || '操作失败');
    }
  } catch (error) {
    console.error('切换设备状态失败:', error);
    ElMessage.error('操作失败');
  }
};

// 确认删除设备
const confirmDeleteDevice = (id) => {
  ElMessageBox.confirm('确定要删除该设备吗？此操作不可恢复。', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    performDeleteDevice(id);
  }).catch(() => {});
};

// 执行删除设备
const performDeleteDevice = async (id) => {
  try {
    const { data } = await deleteDevice(id);
    if (data.code === 200) {
      ElMessage.success('删除设备成功');
      fetchDevices();
    } else {
      ElMessage.error(data.message || '删除设备失败');
    }
  } catch (error) {
    console.error('删除设备失败:', error);
    ElMessage.error('删除设备失败');
  }
};

// 刷新列表
const refreshList = () => {
  fetchDevices();
  ElMessage.success('设备列表已刷新');
};

// 处理搜索
const handleSearch = () => {
  pagination.current = 1;
  fetchDevices();
};

// 分页方法
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  fetchDevices();
};

const handleCurrentChange = (page) => {
  pagination.current = page;
  fetchDevices();
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '未知';
  const date = new Date(dateTime);
  return date.toLocaleString();
};

// 获取设备类型文本
const getDeviceTypeText = (type) => {
  const typeMap = {
    'LCD_SCREEN': 'LCD屏幕',
    'LED_DISPLAY': 'LED显示屏',
    'DIGITAL_SIGNAGE': '数字标牌',
    'TOUCH_SCREEN': '触摸屏',
    'INTERACTIVE_KIOSK': '信息亭',
    'OTHER': '其他'
  };
  return typeMap[type] || '未知';
};

onMounted(() => {
  fetchDevices();
});
</script>

<style scoped>
.device-list-container {
  padding: 20px;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.left-actions,
.right-actions {
  display: flex;
  align-items: center;
}

.list-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>